import Dexie from 'dexie';
import type {Table} from "dexie";
// 定义 GroupDB 类
class GroupDB extends Dexie {
  groupInfoTab!: Table<groupInfoType>;
  
  constructor(dnName:string) {
    super(dnName);
    this.version(1).stores({
      groupInfoTab:'_group_account,_session_id'
    });
  }
}
let timer:number = 0;
export let groupDB:GroupDB ;
/**
 * 添加群信息到数据库
 * @param {groupInfoType} group - 群信息对象
 * @return {Promise<boolean>} - 添加成功返回 true，否则返回 false
 */
export const addGroupToDB = async (group:groupInfoType):Promise<boolean> => {
  if (!groupDB) {
    return false;
  }
  try {
    await groupDB.groupInfoTab.put(group);
    return true;
  } catch (e) {
    return false;
  }
}

export const addGroupListToDB = async (groupList:groupInfoType[]):Promise<boolean> => {
  if (!groupDB) {
    return false;
  }
  try {
    for (let i = 0; i < groupList.length; i++) {
      await groupDB.groupInfoTab.put(groupList[i]);
    }
    return true;
  } catch (e) {
    return false;
  }
}
/**
 * 更新用户信息到数据库
 * @return {Promise<boolean>} - 更新成功返回 true，否则返回 false
 * @param group
 */
export const updateGroupToDB = async (group:groupInfoType):Promise<boolean> => {
  if (!groupDB) {
    return false;
  }
  try {
    await groupDB.groupInfoTab.update(group._group_account, group);
    return true;
  } catch (e) {
    return false;
  }
}

/**
 * 根据账号获取用户信息
 * @return {Promise<groupInfoType|undefined>} - 返回用户信息对象或 undefined
 * @param _group_account
 */
export const getGroupInfoFromDB = async (_group_account:string):Promise<groupInfoType|undefined> => {
  let result:groupInfoType|undefined = undefined;
  if (!groupDB) {
    return result;
  }
  try {
    result = await groupDB.groupInfoTab.get(_group_account);
    return result;
  } catch (e) {
    return result;
  }
}
// 初始化 groupDB
timer = setInterval(() => {
  if (!groupDB) {
    groupDB = new GroupDB(`socketChatGroupInfo`);
    return;
  }
  clearInterval(timer);
},10);
